package com.tucc.hello.leetcode.no1_400.no1_200.no41_60.no57;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] intervals = {{1, 5}, {6, 8}};
        int[] newInterval = {0, 9};
        int[][] result = solution.insert(intervals, newInterval);
        solution.printArr(result);
    }

    public int[][] insert(int[][] intervals, int[] newInterval) {
        int[][] result = null;
        List<int[]> list = new ArrayList<>();
        boolean merged = false;
        int min = newInterval[0];
        int max = newInterval[1];
        for (int i = 0; i < intervals.length; i++) {
            int[] cur = intervals[i];
            if (merged) {
                list.add(cur);
            } else {
                if (cur[1] < min) {
                    list.add(cur);
                } else if (cur[0] > max) {
                    list.add(new int[]{min, max});
                    list.add(cur);
                    merged = true;
                } // cur[1]>= min && cur[0]<= max
                else {
                    min = Math.min(min, cur[0]);
                    max = Math.max(max, cur[1]);
                }
            }
        }
        if (!merged) {
            list.add(new int[]{min, max});
        }
        result = new int[list.size()][];
        Iterator<int[]> iterator = list.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            result[i++] = iterator.next();
        }
        return result;
    }

    private void printArr(int[][] result) {
        if (result != null) {
            for (int i = 0; i < result.length; i++) {
                System.out.println(result[i][0] + " " + result[i][1]);
            }
        }
    }
}
